﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using STX.Domain.Forms;
namespace System
{
    public static class EnumHelper1
    {

        public static List<CheckBox> GetCheckBoxData<T>(int selectedValue=0)
            where T:struct 
        {
            List<CheckBox> list = new List<CheckBox>();
            Type t = typeof(T);
            if (!t.IsEnum)
            {
                return list;
            }

            FieldInfo[] fis = t.GetFields();
            foreach (var fi in fis)
            {
                if (fi.IsSpecialName) continue;
                var enumName = fi.Name;
                int filedValue = (int)Enum.Parse(t, enumName);
                var filedName = string.Empty;
                bool filedIsChecked = (filedValue & selectedValue) != 0;
                var cas = fi.GetCustomAttributes(true);
                foreach (var ca in cas)
                {
                    if (ca.GetType() == typeof(FieldAttribute))
                    {
                        FieldAttribute fa = ca as FieldAttribute;
                        if (fa != null)
                        {
                            filedName = fa.Name;
                        }
                    }
                }
                list.Add(new CheckBox() { FormName = t.Name, Text = filedName, Value = filedValue.ToString(), Checked=filedIsChecked });
            }
            return list;
        }

        public static List<DropDownList> GetDropDownListData<T>(int selectedValue = 0)
            where T : struct
        {
            var list = new List<DropDownList>();
            Type t = typeof(T);
            if (!t.IsEnum)
            {
                return list;
            }

            FieldInfo[] fis = t.GetFields();
            foreach (var fi in fis)
            {
                if (fi.IsSpecialName) continue;
                var enumName = fi.Name;
                int filedValue = (int)Enum.Parse(t, enumName);
                var filedName = string.Empty;
                bool filedIsSelected = filedValue == selectedValue;
                var cas = fi.GetCustomAttributes(true);
                foreach (var ca in cas)
                {
                    if (ca.GetType() == typeof(FieldAttribute))
                    {
                        var fa = ca as FieldAttribute;
                        if (fa != null)
                        {
                            filedName = fa.Name;
                        }
                    }
                }
                list.Add(new DropDownList() { FormName = t.Name, Text = filedName, Value = filedValue.ToString(), Selected = filedIsSelected });
            }
            return list;
        }
    }
}
